<template>
  <div>
    <div class="u-df-st u-base-fg u-pl20 u-mb20">
      <el-radio-group v-model="radio" size="small" class="radio" @input="projectTypeChange">
        <el-radio-button label="JC">监测机构</el-radio-button>
        <el-radio-button label="TG">托管机构</el-radio-button>
      </el-radio-group>
      <AreaForm
        ref="areaFormRef"
        :projectType="radio"
        :reset="reset"
        :propParams="true"
        @handleQuery="handleQuery"
        @resetQuery="resetQuery"
        :isStage="true"
        :showType="radio === 'TG' ? true : false"
        style="margin-bottom: 0px"
      />
    </div>

    <el-row class="row-bg">
      <el-col :span="8">
        <div class="u-h100 u-base-fg u-br4 ce-gauge mr20">
          <div class="u-df-spb u-pl20 u-pr20 u-pt20">
            <span class="u-fs16 u-fw-b">碳排总览</span>
          </div>
          <el-divider />
          <div class="u-df-ed u-primary cursor u-mr20" @click="drawer = true">
            <span class="u-mr6 u-fs14">配额管理</span>
            <i class="el-icon-setting"></i>
          </div>
          <div>
            <el-drawer title="配额管理" :visible.sync="drawer" @open="handleOpen" :direction="fangxiang"
              class="drawerTitle" >
              <div class="drawer-content u-base-fg container">
                <div class="left-side">
                  <el-form :model="formData" label-width="60px" ref="formData">
                    <el-form-item :label="`年份`">
                      <el-date-picker v-model="selectedYear" type="year" format="yyyy" value-format="yyyy"
                        placeholder="选择年份" style="width: 100%; margin-bottom: 20px" @change="handleYearChange1">
                      </el-date-picker>
                    </el-form-item>
                    <el-form-item :label="`1月`">
                      <el-input placeholder="请输入内容" v-model="formOpts.formData.month1"></el-input>
                    </el-form-item>
                    <el-form-item :label="`2月`">
                      <el-input placeholder="请输入内容" v-model="formOpts.formData.month2"></el-input>
                    </el-form-item>
                    <el-form-item :label="`3月`"">
                    <el-input placeholder=" 请输入内容" v-model="formOpts.formData.month3"></el-input>
                    </el-form-item>
                    <el-form-item :label="`4月`">
                      <el-input placeholder="请输入内容" v-model="formOpts.formData.month4"></el-input>
                    </el-form-item>
                    <el-form-item :label="`5月`">
                      <el-input placeholder="请输入内容" v-model="formOpts.formData.month5"></el-input>
                    </el-form-item>
                    <el-form-item :label="`6月`">
                      <el-input placeholder="请输入内容" v-model="formOpts.formData.month6"></el-input>
                    </el-form-item>
                    <el-form-item :label="`7月`">
                      <el-input placeholder="请输入内容" v-model="formOpts.formData.month7"></el-input>
                    </el-form-item>
                    <el-form-item :label="`8月`">
                      <el-input placeholder="请输入内容" v-model="formOpts.formData.month8"></el-input>
                    </el-form-item>
                    <el-form-item :label="`9月`">
                      <el-input placeholder="请输入内容" v-model="formOpts.formData.month9"></el-input>
                    </el-form-item>
                    <el-form-item :label="`10月`">
                      <el-input placeholder="请输入内容" v-model="formOpts.formData.month10"></el-input>
                    </el-form-item>
                    <el-form-item :label="`11月`">
                      <el-input placeholder="请输入内容" v-model="formOpts.formData.month11"></el-input>
                    </el-form-item>
                    <el-form-item :label="`12月`">
                      <el-input placeholder="请输入内容" v-model="formOpts.formData.month12"></el-input>
                    </el-form-item>
                  </el-form>
                </div>
                <div class="divider"></div>
                <div class="right-side">
                  <el-form :model="formData" label-width="60px" ref="formData">
                    <el-form-item :label="`年份`">
                      <el-date-picker v-model="historyYear" type="year" placeholder="选择年份" format="yyyy"
                        value-format="yyyy" style="width: 100%; margin-bottom: 20px" @change="handleYearChange2">
                      </el-date-picker>
                    </el-form-item>
                    <el-form-item :label="`1月`">
                      <el-input placeholder="请输入内容" v-model="formOpts2.formData.month1" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item :label="`2月`">
                      <el-input placeholder="请输入内容" v-model="formOpts2.formData.month2" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item :label="`3月`"">
                    <el-input placeholder=" 请输入内容" v-model="formOpts2.formData.month3" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item :label="`4月`">
                      <el-input placeholder="请输入内容" v-model="formOpts2.formData.month4" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item :label="`5月`">
                      <el-input placeholder="请输入内容" v-model="formOpts2.formData.month5" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item :label="`6月`">
                      <el-input placeholder="请输入内容" v-model="formOpts2.formData.month6" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item :label="`7月`">
                      <el-input placeholder="请输入内容" v-model="formOpts2.formData.month7" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item :label="`8月`">
                      <el-input placeholder="请输入内容" v-model="formOpts2.formData.month8" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item :label="`9月`">
                      <el-input placeholder="请输入内容" v-model="formOpts2.formData.month9" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item :label="`10月`">
                      <el-input placeholder="请输入内容" v-model="formOpts2.formData.month10" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item :label="`11月`">
                      <el-input placeholder="请输入内容" v-model="formOpts2.formData.month11" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item :label="`12月`">
                      <el-input placeholder="请输入内容" v-model="formOpts2.formData.month12" :disabled="true"></el-input>
                    </el-form-item>
                  </el-form>
                </div>
              </div>
                <div class="u-fs12 u-sec-text u-tips u-base-fg span-container" style="flex:auto">
                <div class="u-base-fg ">
                  <el-icon>
                    <InfoFilled />
                  </el-icon>
                  <span class="ml">说明</span>
                </div>
                <span>1.配额输入规则：输入值为正数，如有小数位保留二位。</span>
                <span>2.年度碳配额，逐月分解至12个月输入配额（限额）数值，12个月均已输入完成后，统一计算年度合计值</span>
              </div>

              <div  class="u-base-fg container" >
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="handleSave">保存</el-button>
              </div>
            </el-drawer>
          </div>
          <div class="u-pl20 u-pr20 u-pb20">
            <CECharts v-loading="ovLoading" type="bar" :options="ovOpts" style="margin-left: 100px" />
            <div class="flex-container">
              <div>
                <span class="item">
                  实际碳排
                  <span style="color: #78dc21">{{ ovData?.realCo ?? '-' }}</span>
                  tco2
                </span>
                <el-divider direction="vertical" class="custom-divider"></el-divider>
                <span class="item">
                  碳排配额
                  <span style="color: #78dc21">{{ ovData?.quotaCo ?? '-' }}</span>
                  tco2
                </span>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <!-- <el-col v-if="radio == 'TG'" :span="8">
        <div class="u-h100 u-base-fg u-br4 ce-gauge chart-hight mr20">
          <div class="u-df-spb u-pl20 u-pr20 u-pt20">
            <span class="u-fs16 u-fw-b">综合节能减排统计</span>
          </div>
          <el-divider />
          <div class="u-p20">
            <CECharts v-loading="saveLoading" type="bar" :options="saveOpts" style="height: 240px" ref="pieChartsRef" />
            <div class="flex-container"></div>
          </div>
        </div>
      </el-col> -->

      <el-col v-if="radio == 'TG'" :span="8">
        <div class="u-h100 u-base-fg u-br4 ce-gauge chart-hight mr20" style="height: 345px">
          <div class="u-df-spb u-pl20 u-pr20 u-pt20">
            <span class="u-fs16 u-fw-b">综合节能减排统计</span>
          </div>
          <el-divider />
          <div class="u-p20">
            <CECharts v-loading="saveLoading" type="bar" :options="saveOpts" :key="chartKey" />
          </div>
        </div>
      </el-col>
      <el-col v-if="radio == 'TG'" :span="8">
        <div class="u-h100 u-base-fg u-br4 ce-gauge chart-hight" style="height: 345px">
          <div class="u-df-spb u-pl20 u-pr20 u-pt20">
            <span class="u-fs16 u-fw-b">综合能源碳排占比</span>
          </div>
          <el-divider />
          <div class="u-p20">
            <CECharts v-loading="rateLoading" type="bar" :options="rateOpts" />
          </div>
        </div>
      </el-col>
      <el-col v-if="radio == 'JC'" :span="16">
        <div class="u-h100 u-base-fg u-br4 ce-gauge chart-hight">
          <div class="u-df-spb u-pl20 u-pr20 u-pt20">
            <span class="u-fs16 u-fw-b">碳排占比</span>
          </div>
          <el-divider />
          <div class="u-p20">
            <CECharts v-loading="kpLoading" type="pie" :options="kpOpts" ref="pieChartsRef" />
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 报表 -->
    <!-- <el-card></el-card> -->
    <div class="u-base-fg mt20">
      <div class="u-df-spb u-pl20 u-pr20 u-pt20">
        <div class="u-fs16 u-fw-b">综合碳排趋势</div>
        <el-form :model="tableOverview" :inline="true" class="echartsForm u-df-spb">
          <el-form-item>
            <el-form-item v-if="rangeType[tableOverview.dateType].type !== 'yearrange'">
              <el-date-picker
                v-model="dateRange"
                :type="rangeType[tableOverview.dateType].type ?? 'daterange'"
                :key="rangeType[tableOverview.dateType].type ?? 'daterange'"
                :value-format="rangeType[tableOverview.dateType].fmt ?? 'yyyy-MM-dd'"
                :picker-options="rangeType[tableOverview.dateType].pickerOptions"
                :clearable="false"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="mini"
                align="left"
                class="u-mr10"
                style="width: 240px"
                @change="tableDateChange"
              />
            </el-form-item>
            <el-form-item v-else>
              <el-date-picker
                v-model="yearRange.sYear"
                type="year"
                value-format="YYYY"
                :picker-options="pickerOptsStart"
                placeholder="开始年份"
                size="mini"
                clearable
                style="width: 115px"
                class="u-mr5"
                @change="yearChange"
              />
              <el-date-picker
                v-model="yearRange.eYear"
                type="year"
                value-format="YYYY"
                :picker-options="pickerOpts"
                placeholder="结束年份"
                size="mini"
                clearable
                style="width: 115px"
                @change="yearChange"
              />
            </el-form-item>
          </el-form-item>
          <el-form-item prop="dateType" class="u-df-ct">
            <el-radio-group v-model="tableOverview.dateType" size="mini" @input="tableDateTypeChange">
              <el-radio-button label="m">月</el-radio-button>
              <el-radio-button label="y">年</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <el-divider />
      <div class="u-p20">
        <CECharts ref="ceChart" v-loading="tableLoading" type="line" :options="trOpts" style="height: 360px" />
      </div>
    </div>

    <div class="contBox">
      <div class="u-df-spb mb20">
        <div class="u-fs16 u-fw-b">{{ proName }}机构碳排情况</div>
        <el-button type="primary" plain size="small" @click="handleExport">导出</el-button>
      </div>
      <TableList
        v-loading="tableLoading"
        :total="total"
        :height="500"
        :tableData="tableData"
        :pageObj="pageObj"
        :columObj="columObj"
        @getList="getList"
      >
        <TableList
          v-loading="tableLoading"
          :total="total"
          :height="500"
          :tableData="tableData"
          :pageObj="pageObj"
          :columObj="columObj"
          @getList="getList"
        ></TableList>

        <template v-slot:bExceed="{ scope }">
          <span v-if="scope.row.energyBasisValue || scope.row.energyBasisValueGap">
            {{ scope.row.energyBasisValue | nullishCoalescing }}/{{ scope.row.energyBasisValueGap | nullishCoalescing }}
          </span>
          <span v-if="!scope.row.energyBasisValue && !scope.row.energyBasisValueGap">--</span>
        </template>
        <template v-slot:gExceed="{ scope }">
          <span v-if="scope.row.energyGuideValue || scope.row.energyGuideValueGap">
            {{ scope.row.energyGuideValue | nullishCoalescing }}/{{ scope.row.energyGuideValueGap | nullishCoalescing }}
          </span>
          <span v-if="!scope.row.energyGuideValue && !scope.row.energyGuideValueGap">--</span>
        </template>
        <template v-slot:uExceed="{ scope }">
          <span v-if="scope.row.energyUpperValue || scope.row.energyUpperValueGap">
            {{ scope.row.energyUpperValue | nullishCoalescing }}/{{ scope.row.energyUpperValueGap | nullishCoalescing }}
          </span>
          <span v-if="!scope.row.energyUpperValue && !scope.row.energyUpperValueGap">--</span>
        </template>
        <template v-slot:jzExceed="{ scope }">
          <span v-if="scope.row.energyBasisCost || scope.row.energyBasisCostGap">
            {{ scope.row.energyBasisCost | nullishCoalescing }}/{{ scope.row.energyBasisCostGap | nullishCoalescing }}
          </span>
          <span v-if="!scope.row.energyBasisCost && !scope.row.energyBasisCostGap">--</span>
        </template>
      </TableList>
    </div>
  </div>
</template>

<script setup>
import dayjs from 'dayjs';
import { cloneDeep, forEach, merge } from 'lodash-es';
import { useRequest } from '@/hooks/requestHooks';
import { useWatch } from '@/hooks/useWatch';
import { useDownload } from '@/hooks/tool.js';
import { usePickerOption } from '@/views/hooks';
import { useMain } from '@/store/app.js';
import { Message, MessageBox } from 'element-ui';
import {
  getCarbonBudget,
  getEnegySave,
  getCarbonRateTG,
  getEnergyList,
  getCarbonTable,
  getCarbonRateJC,
  queryQuota,
  insertQuota,
} from '@/api/index.js';
import {  basicLineYAxis } from '@/components/chart/options/baseOptions.js';
import { TableList } from '@/components/MainComponents.js';
import AreaForm from '@/views/components/AreaForm.vue';
import CECharts from '@/components/chart/CECharts.vue';

const { proxy } = getCurrentInstance();
const chartKey = ref(0);
const chartKey2 = ref(0);
const drawer = ref(false);
const fangxiang = ref('rtl');
const pieChartsRef = ref(null);
const proName = ref('托管');
const commonRule = [{ required: true, message: '请输入', trigger: 'blur' }];
const handleOpen = () => {
  peieParam.value.year = ref(dayjs().subtract(0, 'year').format('YYYY'));
  peieParam2.value.year = ref(dayjs().subtract(1, 'year').format('YYYY'));
  peieParam.value.projectType = tableOverview.value.projectType;
  peieParam2.value.projectType = tableOverview.value.projectType;

  selectedYear.value = ref(dayjs().subtract(0, 'year').format('YYYY'));
  historyYear.value = ref(dayjs().subtract(1, 'year').format('YYYY'));

  console.log('打开' + peieParam.value.year);
  runOpen(peieParam.value);
  runOpen2(peieParam2.value);
};
const formOpts = reactive({
  ref: null,
  labelWidth: '70px',
  formData: {
    enterpriseCode: null,
    projectType: null,
    year: dayjs().format('YYYY'),
    month1: null,
    month2: null,
    month3: null,
    month4: null,
    month5: null,
    month6: null,
    month7: null,
    month8: null,
    month9: null,
    month10: null,
    month11: null,
    month12: null,
  },
  rules: {
    year: [{ required: true, message: '请选择年份', trigger: 'blur' }],
    month1: commonRule,
    month2: commonRule,
    month3: commonRule,
    month4: commonRule,
    month5: commonRule,
    month6: commonRule,
    month7: commonRule,
    month8: commonRule,
    month9: commonRule,
    month10: commonRule,
    month11: commonRule,
    month12: commonRule,
  },
});
const formOpts2 = reactive({
  ref: null,
  labelWidth: '70px',
  formData: {
    year: dayjs().format('YYYY'),
    month1: null,
    month2: null,
    month3: null,
    month4: null,
    month5: null,
    month6: null,
    month7: null,
    month8: null,
    month9: null,
    month10: null,
    month11: null,
    month12: null,
  },
});
const selectedYear = ref(dayjs().subtract(0, 'year').format('YYYY'));
const historyYear = ref(dayjs().subtract(1, 'year').format('YYYY'));

const formData = {
  month1: '',
  month2: '',
  month3: '',
  month4: '',
  month5: '',
  month6: '',
  month7: '',
  month8: '',
  month9: '',
  month10: '',
  month11: '',
  month12: '',
};
const peieParam = ref({ year: null, projectType: null });
const peieParam2 = ref({ year: null, projectType: null });

const handleYearChange1 = () => {
  peieParam.value.year = selectedYear;
  debugger;
  peieParam.value.projectType = tableOverview.value.projectType;
  runOpen(peieParam.value);
};
const handleYearChange2 = () => {
  peieParam2.value.year = historyYear;
  peieParam2.value.projectType = tableOverview.value.projectType;
  runOpen2(peieParam2.value);
};
// 碳排总览
const dateTypeConfig = {
  m: {
    type: 'month',
    fmt: 'yyyy-MM',
    default: dayjs().format('YYYY-MM'),
  },
  y: {
    type: 'year',
    fmt: 'yyyy',
    default: dayjs().format('YYYY'),
  },
};

const ceOverview = ref({
  dateType: 'y',
  queryDate: dateTypeConfig.y.default,
  inId: null,
});

const colors = ['#76E612', '#EDA422', '#EE6666'];
const trOpts = ref({
  color: colors,
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
    },
  },
  grid: {
    right: '2%',
    left: '2%',
  },
  legend: {
    data: ['碳排总量', '碳排配额'],
  },
  xAxis: [
    {
      type: 'category',
      axisTick: {
        alignWithLabel: true,
      },
      // prettier-ignore
      data: [],
    },
  ],
  yAxis: [
    {
      type: 'value',
      name: '单位：tCo2e',
    },
  ],
  series: [
    {
      name: '碳排总量',
      type: 'bar',
      data: [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
      barWidth:25,
    },
    {
      name: '碳排配额',
      type: 'line',
      smooth: true,
      data: [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2],
    },

  ],
});
const projectTypeChange = val => {
  tableOverview.value.projectType = val;
  if ('TG' === val) {
    proName.value = '托管';
    columObj.value.columnData = columnData1;
  } else {
    proName.value = '监测';
    columObj.value.columnData = columnData2;
  }
  // tableOverview.value.dateType = 'm';
  // dateRange.value = rangeType.value.m.default;
  // console.log();
  if (tableOverview.value.dateType === 'm') {
    tableOverview.value.startDate = rangeType.value.m.default[0];
    tableOverview.value.endDate = rangeType.value.m.default[1];
    dateRange.value[0] = rangeType.value.m.default[0];
    dateRange.value[1] = rangeType.value.m.default[1];
  }

  // tableOverview.value.startDate = rangeType.value.m.default[0];
  // tableOverview.value.endDate = rangeType.value.m.default[1];
  // tableOverview.dateType = 'm';
  nextTick(() => {
    searchQuery();
    if (tableOverview.value.dateType === 'y') {
      tableOverview.value.startDate = rangeType.value.y.default[0];
      tableOverview.value.endDate = rangeType.value.y.default[1];
      (yearRange.value.sYear = dayjs().subtract(2, 'year').format('YYYY')), dayjs().format('YYYY');
      (yearRange.value.eYear = dayjs().subtract(0, 'year').format('YYYY')), dayjs().format('YYYY');
    }
    dateRange.value = rangeType.value.m.default;
    if ('TG' === val) {
    } else {
      setTimeout(() => {
        pieChartsRef.value.$$chart.resize();
      }, 500);
      console.log(pieChartsRef.value, 'pieChartsRef.value');
    }
  });
};
;
const currentRatio = ref(0);
const { projectType } = useMain();
// 总览chart option
const ovOpts = ref({
  tooltip: { show: true },
  series: [
    {
      type: 'gauge',
      center: ['32%', '50%'],
      radius: '100px',
      pointer: { length: '55%' },
      progress: { show: true, width: 13 },
      axisLine: {
        lineStyle: {
          width: 13,
          color: [
            // 指针未走过的区域为灰色
            [1, '#178db9'],
          ],
        },
      },
      splitLine: { distance: 5 },
      axisTick: { distance: 5 },
      axisLabel: { distance: 15, color: '#7f889a' },
      itemStyle: { color: '#f75e41' },
      detail: {
        formatter: '{value}%',
        color: '#f65d45',
        fontSize: 24,
        offsetCenter: [0, '36%'],
      },
      title: {
        offsetCenter: [0, '64%'],
        color: '#7f889a',
        fontSize: 14,
      },
      data: [{ value: 0, name: '当前占比' }],
    },
  ],
});
const rateOpts = ref({
  title: {
    text: '',
    left: '20%',
    top: '50%',
    textAlign: 'center',
    textVerticalAlign: 'middle',
    textStyle: {
      rich: {
        a: {
          fontSize: 15,
          color: '#FF0000', // 红色
          fontWeight: 'bold',
        },
        b: {
          fontSize: 15,
          color: '#696e83',
          padding: [0, 0, 0, 10], // 左边填充以分隔两个部分
        },
      },
    },
  },
  tooltip: {
    trigger: 'item',
  },
  legend: {
    orient: 'vertical',
    left: 'right',
    top: 'center',
    align: 'left',
  },
  series: [
    {
      center: ['21%', '50%'],
      type: 'pie',
      radius: ['60%', '80%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center',
      },
      emphasis: {
        label: {
          show: false,
          fontSize: 40,
          fontWeight: 'bold',
        },
      },
      labelLine: {
        show: false,
      },
      data: [],
    },
  ],
});
const saveOpts = ref({
  xAxis: [{
    type: 'value',
    // 不显示X轴的线条
    axisLine: {
      show: false,
    },
    axisLabel: {
      show: false,
    },
    axisTick: {
      show: false, // 隐藏y轴刻度线
    },
    splitLine: { show: false },
  }],
  yAxis: [{
    type: 'category',
    data: ['累计减排量(tCo2e)', '总节能量(tce)'],
    // 不显示X轴的线条
    axisLine: {
      show: false,
    },
    axisTick: {
      show: false, // 隐藏y轴刻度线
    },
    splitLine: { show: false },
  }],
  series: [
    {
      barWidth: '30%', // 设置柱子宽度
      type: 'bar',
      // 定义每个柱子的颜色
      itemStyle: {
        color: function (params) {
          // 颜色列表
          var colorList = ['#37a357', '#c23531'];
          return colorList[params.dataIndex];
        },
      },
      label: {
        show: true,
        position: 'right', // 设置标签的位置在柱子的顶部
        color:'#fff'
      },
      data: [],
    },
  ],
});
const tableOverview = ref({
  dateType: 'm',
  startDate: dayjs().subtract(6, 'month').format('YYYY-MM'),
  endDate: dayjs().subtract(1, 'month').format('YYYY-MM'),
  inId: null,
  projectType: 'TG',
});
const kpOpts = ref({
  color: ['#01b0fd', '#76e612', '#efef12', '#e87f16', '#8F8FBD'],
  grid: [
    {
      left: '5%',
      right: '55%',
      top: '10%',
      bottom: '10%',
    },
    {
      left: '45%',
      right: '15%',
      top: '10%',
      bottom: '10%',
    },
  ],
  title: [
    {
      bottom: 0,
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
      },
      text: '能源碳排占比',
      left: '8%',
    },
    {
      bottom: 0,
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
      },
      text: '设备系统碳排占比',
      right: '27%',
    },
  ],
  legend: [
    {
      type: 'scroll',
      show: true,
      orient: 'vertical',
      top: 'middle',
      x: null,
      y: null,
      orient: 'vertical', // 垂直布局
      left: '25%', // 距离右侧10%
      top: 'center', // 垂直居中
      itemWidth: 10,
      itemHeight: 10,
      padding: [0, 820, 0, 0],
      itemStyle: {
        borderWidth: 0,
      },
      textStyle: {
        color: '#7f889a',
      },
      data: [],
    },
    {
      type: 'scroll',
      show: true,
      orient: 'vertical',
      top: 'middle',
      x: null,
      y: null,
      orient: 'vertical', // 垂直布局
      left: '25%', // 距离右侧10%
      top: 'center', // 垂直居中
      itemWidth: 10,
      padding: [0, 320, 0, 550],
      itemHeight: 10,
      itemStyle: {
        borderWidth: 0,
      },
      textStyle: {
        color: '#7f889a',
      },
      data: [],
    },
  ],
  series: [
    {
      type: 'pie',
      radius: ['40%', '60%'],
      center: ['25%', '45%'],
      label: {
        overflow: 'break',
        color: '#7f889a',
        show: false,
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)',
        },
      },
      labelLine: {
        normal: {
          show: false, // 隐藏从扇区到标签的指引线（通常这条线不是到图例的指引线，但也可以隐藏）
        },
      },
      data: [],
      top: 0,
      bottom: 0,
      name: '能源碳排占比',
      left: 0,
      right: '50%',
    },
    {
      type: 'pie',
      radius: ['40%', '60%'],
      center: ['5%', '45%'],
      label: {
        overflow: 'break',
        color: '#7f889a',
        show: false,
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)',
        },
      },
      labelLine: {
        normal: {
          show: false, // 隐藏从扇区到标签的指引线（通常这条线不是到图例的指引线，但也可以隐藏）
        },
      },
      data: [],
      top: 0,
      bottom: 0,
      name: '设备系统碳排占比',
      left: '65%',
      right: 0,
    },
  ],
});
const columnData1 = [
  {
    text: true,
    prop: 'num',
    label: '序号',
  },
  {
    text: true,
    prop: 'staticTime',
    label: '统计时间',
  },
  {
    text: true,
    prop: 'quota',
    label: '碳排配额',
  },
  {
    text: true,
    prop: 'energyConsumeValue',
    label: '实际碳排',
  },
  {
    text: true,
    prop: 'jieneng',
    label: '节能量',
  },
  {
    text: true,
    prop: 'jienengjianpailiang',
    label: '节能减排量',
  },
];
const columnData2 = [
  {
    text: true,
    prop: 'num',
    label: '序号',
  },
  {
    text: true,
    prop: 'staticTime',
    label: '统计时间',
  },
  {
    text: true,
    prop: 'quota',
    label: '碳排配额',
  },
  {
    text: true,
    prop: 'energyConsumeValue',
    label: '碳排总量',
  },
];
const dimensions0 = [
  'energyValueDate',
  { name: 'energyConsumeValue', displayName: '实际能耗' },
  { name: 'energyBasisValue', displayName: '基准能耗' },
];
const dimensions1 = [
  'energyValueDate',
  { name: 'energyConsumeCost', displayName: '实际能耗费用' },
  { name: 'energyBasisCost', displayName: '基准能耗费用' },
];
const radio = ref(projectType);
const rangeType = ref({
  m: {
    type: 'monthrange',
    fmt: 'yyyy-MM',
    // default: [],
    default: [dayjs().subtract(6, 'month').format('YYYY-MM'), dayjs().subtract(1, 'month').format('YYYY-MM')],
    pickerOptions: usePickerOption('m'),
  },
  y: {
    type: 'yearrange',
    fmt: 'yyyy',
    // default: [],
    default: [dayjs().subtract(2, 'year').format('YYYY'), dayjs().format('YYYY')],
  },
});
const dateRange = ref(rangeType.value.m.default);
const yearRange = ref({ sYear: null, eYear: null });
const total = ref(0);
const tableData = ref([]);
const reset = ref(0);
const tabPosition = ref('nhfx');
const chartParams = ref({
  inId: null,
  energyType: 2,
  // energyType: 0,
  dateStart: dateRange.value[0] ?? '',
  dateEnd: dateRange.value[1] ?? '',
  dateType: 'm',
  projectType: radio.value,
});
const engTypes = ref([]);
const unitList = ref(null);
useRequest(getEnergyList, {
  defaultParams: [{ pageNum: 1, pageSize: 10 }],
  onSuccess: res => {
    engTypes.value = res.rows;
    let obj = {};
    forEach(res?.rows, n => {
      obj[n.id] = n.energyUnit;
    });
    unitList.value = obj;
  },
});
const [ovData, ovLoading, runOv] = useRequest(getCarbonBudget, {
  defaultParams: [tableOverview.value],
  manual: true,
  onSuccess: res => {
    ovOpts.value.series[0].data[0].value = res.data?.ratio ?? 0;
    currentRatio.value = res.data?.ratio ?? 0;
  },
});
const [, , runOpen] = useRequest(queryQuota, {
  defaultParams: [peieParam.value],
  manual: true,
  onSuccess: res => {
    formOpts.formData.month1 = res.data.month1;
    formOpts.formData.month2 = res.data.month2;
    formOpts.formData.month3 = res.data.month3;
    formOpts.formData.month4 = res.data.month4;
    formOpts.formData.month5 = res.data.month5;
    formOpts.formData.month6 = res.data.month6;
    formOpts.formData.month7 = res.data.month7;
    formOpts.formData.month8 = res.data.month8;
    formOpts.formData.month9 = res.data.month9;
    formOpts.formData.month10 = res.data.month10;
    formOpts.formData.month11 = res.data.month11;
    formOpts.formData.month12 = res.data.month12;
  },
});
const [, , runOpen2] = useRequest(queryQuota, {
  defaultParams: [peieParam.value],
  manual: true,
  onSuccess: res => {
    formOpts2.formData.month1 = res.data.month1;
    formOpts2.formData.month2 = res.data.month2;
    formOpts2.formData.month3 = res.data.month3;
    formOpts2.formData.month4 = res.data.month4;
    formOpts2.formData.month5 = res.data.month5;
    formOpts2.formData.month6 = res.data.month6;
    formOpts2.formData.month7 = res.data.month7;
    formOpts2.formData.month8 = res.data.month8;
    formOpts2.formData.month9 = res.data.month9;
    formOpts2.formData.month10 = res.data.month10;
    formOpts2.formData.month11 = res.data.month11;
    formOpts2.formData.month12 = res.data.month12;
  },
});
const [, , runClose] = useRequest(insertQuota, {
  defaultParams: [formOpts.value],
  manual: true,
  onSuccess: res => {
    Message.success(res.msg);
  },
});
const [, saveLoading, runSave] = useRequest(getEnegySave, {
  defaultParams: [tableOverview.value],
  manual: true,
  onSuccess: res => {
    let a = 0;
    let b = 0;
    a = res.data.subQuantity;
    b = res.data.saveQuantity;
    chartKey.value += 1;
    saveOpts.value.series[0].data[0] = a;
    saveOpts.value.series[0].data[1] = b;
  },
});

const [, rateLoading, runRate] = useRequest(getCarbonRateTG, {
  defaultParams: [tableOverview.value],
  manual: true,
  onSuccess: res => {
    const pie2 = [];
    let totalNum = 0;
    for (let index = 0; index < res.data.length; index++) {
      const element = res.data[index];
      pie2.push({ value: element.value, name: element.name });
      totalNum = totalNum + element.value;
    }
    totalNum = totalNum.toFixed(3);

    const total = '{a|' + totalNum + '} \n \n{b|能源碳排总量}';
    rateOpts.value.series[0].data = pie2;
    rateOpts.value.title.text = total;
  },
});
const [, tableLoading, runTable] = useRequest(getCarbonTable, {
  defaultParams: [tableOverview.value],
  manual: true,
  onSuccess: res => {
    tableData.value = res.data;
    const data1 = [];
    const data2 = [];
    const data3 = [];
    for (let index = 1; index < res.data.length; index++) {
      const element = res.data[index];
      data1.push(element.energyConsumeValue);
      data2.push(element.quota);
      data3.push(element.staticTime);
    }
    trOpts.value.series[0].data = data1;
    trOpts.value.series[1].data = data2;
    trOpts.value.xAxis[0].data = data3;
  },
});
const [, kpLoading, runKp] = useRequest(getCarbonRateJC, {
  defaultParams: [tableOverview.value],
  manual: true,
  onSuccess: res => {
    var json = JSON.stringify(kpOpts.value);
    chartKey2.value += 1;
    console.log(chartKey2.value);

    kpOpts.value.series[0].data = res.data?.elec ?? [];
    kpOpts.value.legend[0].data = res.data?.elec ?? [];
    kpOpts.value.series[1].data = res.data?.system ?? [];
    kpOpts.value.legend[1].data = res.data?.system ?? [];
  },
});
const pageObj = ref({
  pageNum: 1,
  pageSize: 10,
});
const columObj = ref({
  columnData: [],
});
const tableDateTypeChange = val => {
  (yearRange.value.sYear = dayjs().subtract(2, 'year').format('YYYY')), dayjs().format('YYYY');
  (yearRange.value.eYear = dayjs().subtract(0, 'year').format('YYYY')), dayjs().format('YYYY');
  tableOverview.value.dateType = val;
  if ('y' === val) {
    tableOverview.value.startDate = rangeType.value.y.default[0];
    tableOverview.value.endDate = rangeType.value.y.default[1];
  }
  if ('m' === val) {
    tableOverview.value.startDate = rangeType.value.m.default[0];
    tableOverview.value.endDate = rangeType.value.m.default[1];
  }
  searchQuery();
};
const tableDateChange = val => {
  tableOverview.value.startDate = dateRange.value[0];
  tableOverview.value.endDate = dateRange.value[1];
  searchQuery();
};

const chartOpts = ref({
  grid: {
    bottom: '10%',
    top: '16%',
    left: '5%',
    right: '5%',
    containLabel: true,
  },
  color: ['#4992ff', '#22edcb', '#eda422', '#d222ed'],
  yAxis: [
    merge({}, basicLineYAxis, {
      name: '单位：KWh',
    }),
    { ...basicLineYAxis },
  ],
  series: [],
  dataset: {
    dimensions: [],
    source: [],
  },
  dataZoom: [{ xAxisIndex: [0, 1] }, { xAxisIndex: [0, 1] }],
});
const rulerDate = ref('-');
const conclusion = ref('-');
const rulerList = ref(null);

// 开始时间不能大于结束时间
const pickerOptsStart = ref({
  disabledDate: time => {
    if (yearRange.value.eYear) {
      return (
        dayjs(time) > dayjs(yearRange.value.eYear) || dayjs(time) < dayjs(yearRange.value.eYear).subtract(2, 'year')
      );
    }
  },
});
// 结束时间不能小于开始时间
const pickerOpts = ref({
  disabledDate: time => {
    return dayjs(time) < dayjs(yearRange.value.sYear) || dayjs(time) > dayjs(yearRange.value.sYear).add(2, 'year');
  },
});
const [, loading, run] = useRequest(getCarbonBudget, {
  manual: true,
  onSuccess: async res => {
    chartOpts.value.dataset.source = res?.data ?? [];
    total.value = res.data?.length;
    // tableData.value = res?.data?.slice(0, 10) ?? [];
    chartOpts.value.yAxis[0].name = `单位：${
      chartParams.value.energyType ? unitList.value[chartParams.value.energyType] : ''
    }`;
    let obj = cloneDeep(res?.data[0]);
    rulerDate.value = obj?.energyValueDate;
    conclusion.value = obj?.conclusion;
  },
});

const searchQuery = () => {
  if ('TG' === radio.value) {
    runRate(tableOverview.value);
    runSave(tableOverview.value);
  }
  if ('JC' === radio.value) {
    runKp(tableOverview.value);
  }

  runOv(tableOverview.value);
  runTable(tableOverview.value);

  forEach(rulerList.value, n => {
    n.value = '';
    n.height = null;
  });
  pageObj.value = {
    pageNum: 1,
    pageSize: 10,
  };
};
const yearChange = () => {
  tableOverview.value.startDate = dateRange.value[0];
  tableOverview.value.endDate = dateRange.value[1];
  searchQuery();
};
const handleQuery = queryParams => {
  forEach(rulerList.value, n => {
    n.height = null;
  });
  ceOverview.value.inId = queryParams?.buildingCode?.enterpriseCode ?? null;
  tableOverview.value.inId = queryParams?.buildingCode?.enterpriseCode ?? null;
  searchQuery();
};
const resetQuery = () => {
  forEach(rulerList.value, n => {
    n.height = null;
  });
  dateRange.value = rangeType.value.m.default;
  yearRange.value = { sYear: null, eYear: null };
  chartParams.value = {
    inId: null,
    energyType: 2,
    dateStart: dateRange.value[0],
    dateEnd: dateRange.value[1],
    dateType: 'd',
    projectType: radio.value,
  };
  total.value = 0;
  chartOpts.value.dataset.source = [];
  tableData.value = [];
  searchQuery();
};
const getList = e => {
  pageObj.value.pageNum = e.page;
  pageObj.value.pageSize = e.limit;
  tableData.value = chartOpts.value.dataset?.source.slice((e.page - 1) * e.limit, e.page * e.limit);
};

const handleSave = () => {
  MessageBox.confirm('请确认信息无误', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      formOpts.formData.enterpriseCode = tableOverview.value.inId;
      formOpts.formData.projectType = tableOverview.value.projectType;

      runClose(formOpts.formData);
      handleCancel();
      searchQuery();
    })
    .catch(() => {});
};
const handleCancel = () => {
  drawer.value = false;
};

const handleExport = () => {
  const downloadUrl = '/energyservice/enQuota/getCarbonTableExport';
  useDownload(downloadUrl, tableOverview.value, `碳排分析.xlsx`);
};

useWatch(
  () => chartParams.value.dateType,
  (n, o) => {
    if (n !== o) {
      if (n !== 'y') {
        dateRange.value = rangeType.value.y.default;
        chartParams.value.dateStart = dateRange.value[0] ?? '';
        chartParams.value.dateEnd = dateRange.value[1] ?? '';
      } else {
        yearRange.value.sYear = rangeType.value.y.default[0] ?? '';
        yearRange.value.eYear = rangeType.value.y.default[1] ?? '';
        chartParams.value.dateStart = yearRange.value.sYear ?? '';
        chartParams.value.dateEnd = yearRange.value.eYear ?? '';
      }
      total.value = 0;
      chartOpts.value.dataset.source = [];
      tableData.value = [];
      forEach(rulerList.value, n => {
        n.height = null;
      });
      rulerDate.value = null;
      conclusion.value = null;
    }
  },
);
useWatch(
  radio,
  n => {
    reset.value = reset.value + 1;
    chartParams.value.buildingCode = null;
    chartParams.value.projectType = n;
    columObj.value.columnData = n === 'JC' ? columnData2 : columnData1;
    if (n === 'JC') {
      chartOpts.value.dataset.dimensions = dimensions1;
    } else {
      chartOpts.value.dataset.dimensions = tabPosition.value === 'nhfx' ? dimensions0 : dimensions1;
    }
  },
  { immediate: true },
);
useWatch(
  chartOpts.value.dataset,
  n => {
    chartOpts.value.series = Array.from({ length: n.dimensions.length - 1 }, (_, idx) => {
      return idx === 0
        ? {
            type: 'bar',
            barWidth: 25,
            yAxisIndex: 0,
          }
        : {
            type: 'line',
            smooth: true,
            showSymbol: false,
            yAxisIndex: 0,
          };
    });
  },
  { deep: true },
);
useWatch(
  () => proxy.$store.state.global.setting.sideTheme,
  n => {
    console.log('[ n ] >', n)
    if (n === 'theme-dark') {
      saveOpts.value.series[0].label.color = '#fff';
    } else {
      saveOpts.value.series[0].label.color = '#000';
    }
  },
  { immediate: true },
);
</script>

<style lang="scss" scoped>
.u-mr6{
  margin-right: 6px;
}
.echartsForm :deep(.el-form-item) {
  margin-bottom: 0;
}

.u-pl20 {
  padding-left: 20px;
}

.chartsBox {
  height: 430px;
  position: relative;
}

.chartsLeft {
  width: 65%;
  margin-right: 7%;
  height: 100%;
}

.chartsRight {
  width: 35%;
  height: 100%;

  .unitStyle {
    margin-top: 42px;
    margin-bottom: 30px;
    margin-left: -20px;
  }
}

.rightBox {
  position: relative;

  .rulerBox {
    height: 250px;
    width: 20px;
    border-left: 1px solid #000;
    border-top: 1px solid #000;

    // border-bottom: 1px solid #000;
    li {
      border-bottom: 1px solid #000;
      height: 20%;
    }
  }

  .rulerBox2 {
    position: absolute;
    top: 0;
    height: 250px;
    width: 100px;
  }

  .rValue {
    position: absolute;
    top: 0;
    height: 5px;
    width: 50px;
  }

  .rLabel {
    transform: translate(-120px, -5px);
    font-size: 12px;
    width: 120px;
  }

  .rIntroduce {
    transform: translate(70px, -20px);
    font-size: 12px;
    width: 400px;
  }
}

.app-light .chartsRight .rulerBox,
.app-light .chartsRight .rulerBox li {
  border-color: #000;
  color: #000;
}

.app-dark .chartsRight .rulerBox,
.app-dark .chartsRight .rulerBox li {
  border-color: #fff;
  color: #fff;
}

.tabs {
  position: absolute;
  right: 20px;
  top: 20px;
}

.left-side,
.right-side {
  flex-grow: 1;
  padding: 10px;
}

.divider {
  width: 1px;
  /* 分割线宽度 */
  background-color: #dcdcdc;
  /* 分割线颜色 */
  margin: 0 40px;
  /* 分割线两边的间距 */
}

.drawer-content {
  display: flex;
  height: 100%;
}

.text {
  color: #808080;
}

// ::v-deep .el-drawer__header {
//   text-align: left !important;
//   font-size: 16px !important;
//   background-color: #242b41 !important;
//   margin-bottom: 0 !important;
//   padding: 20px !important;
//   color: #fff;
// }
// ::v-deep .el-drawer__body {
//   background-color: #161e35 !important;
//   padding: 20px !important;
// }
.drawerTitle ::v-deep(.el-drawer__header) {
  height: 80px;
  width: 750px;
}

.app-dark .drawerTitle ::v-deep(.el-drawer__header) {
  text-align: left !important;
  font-size: 16px !important;
  background-color: #242b41 !important;
  margin-bottom: 0 !important;
  padding: 20px !important;
  color: #fff;
}

.flex-container {
  display: flex;
  justify-content: center;
  /* 水平居中 */
  gap: 30px;
  /* 可选：设置项目之间的间距 */
  margin-bottom: 0px;
}

.container {
  display: flex;
  align-items: center;
  gap: 20px;
  /* 垂直居中 */
}

.left-text,
.right-text {
  padding: 0 10px;
  /* 根据需要调整间距 */
}

.divider {
  height: 100%;
  /* 确保分隔线的高度匹配父容器 */
  margin: 0 10px;
  /* 调整分隔线与文本之间的间距 */
}

.chart-hight {
  height: 345px;
}

.grid-container {
  display: flex;
  justify-content: space-evenly;
  /* 让每个元素之间的间距相等 */
}

.divider {
  margin-bottom: 10px;
  /* 调整分隔线与文本之间的间距 */
}

.custom-divider {
  margin: 0 20px;
  /* 设置分隔线左右两边的间距 */
}

.chart-container {
  margin-left: 100px;
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
}

.span-container {
  display: flex;
  flex-direction: column;
  align-items: left;
  justify-content: center;
  height: 60px; /* 设置容器高度以方便观察垂直排列效果 */
}
</style>
